<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input placeholder="试题名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="dialogFormVisible = true">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="users" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="id" prop="id" width="60" label="ID">
			</el-table-column>
			<el-table-column prop="testTitle" label="考试题目" width="180" sortable>
			</el-table-column>
			<el-table-column prop="testNumber" label="考试题目数量" width="200" sortable>
			</el-table-column>
			<el-table-column prop="testTime" label="考试时间" width="200" sortable>
			</el-table-column>
			<el-table-column label="操作" width="120" sortable>
				<template slot-scope="scope">
					<el-button size="small" type="info" @click="Automatic(scope.row)">判卷</el-button>
				</template>
			</el-table-column>
			<el-table-column label="操作" min-width="180">
				<template slot-scope="scope">
					<el-button size="small" @click="viewTest(scope.row)">查看</el-button>
					<el-button size="small" type="primary" @click="updateTestClick(scope.row)">修改</el-button>
					<el-button type="danger" size="small" @click="deltestClick(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--新增的弹出框-->
		<el-dialog title="新增面试题" :visible.sync="dialogFormVisible" class="box">
			<el-form :model="addForm" :rules="rules" ref="addForm" class="demo-ruleForm">
				<div class="addFormPart left">
					<el-form-item label="考试题目" :label-width="formLabelWidth" prop="testTitle">
						<el-input v-model="addForm.testTitle" placeholder="请输入考试题目"></el-input>
					</el-form-item>
					<el-form-item label="考试题数量" :label-width="formLabelWidth" prop="testNumber">
						<el-input v-model="addForm.testNumber" type="number" placeholder="请输入考试题数量" @change="numChange(addForm.testNumber)">
						</el-input>
					</el-form-item>
					<el-form-item label="考试时间" :label-width="formLabelWidth" prop="testTime">
						<el-input v-model="addForm.testTime" placeholder="请输入考试时间">
						</el-input>
					</el-form-item>
				</div>
				<div class="addFormPart right">
					<el-form-item v-for="list in addForm.testNumber" prop="testDesc" :key="list" :label-width="formLabelWidth2">
						<div class="title-line">&nbsp;{{list+'、题目'}}</div>
						<el-input class="right" type="textarea" v-model="addForm.testDesc[list-1]"></el-input>
					</el-form-item>
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetForm('addForm')">重置</el-button>
				<el-button type="primary" @click="addAnsClick('addForm')">确 定</el-button>
			</div>
		</el-dialog>

		<!-- 修改面试题 -->
		<el-dialog title="修改面试题" :visible.sync="dialogFormVisibleUpdate" :before-close="handleClose">
			<el-form :model="updateForm" :rules="rules2" ref="updateForm" class="demo-ruleForm">
				<div class="addFormPart">
					<el-form-item label="考试题目" :label-width="formLabelWidth" prop="testTitle">
						<el-input v-model="updateForm.testTitle" placeholder="请输入考试题目"></el-input>
					</el-form-item>
					<el-form-item label="考试题数量" :label-width="formLabelWidth" prop="testNumber">
						<el-input v-model="updateForm.testNumber" type="number" placeholder="请输入考试题数量" @change="numChange2(updateForm.testNumber)">
						</el-input>
					</el-form-item>
					<el-form-item label="考试时间" :label-width="formLabelWidth" prop="testTime">
						<el-input v-model="updateForm.testTime" placeholder="请输入考试时间">
						</el-input>
					</el-form-item>
				</div>
				<div class="addFormPart">
					<el-form-item v-for="list in updateForm.testNumber" prop="testDesc" :key="list" :label="list+'、'" :label-width="formLabelWidth2">
						<el-input class="right" type="textarea" v-model="updateForm.testDesc[list-1]"></el-input>
					</el-form-item>
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cancleUpdate('updateForm')">重置</el-button>
				<el-button type="primary" @click="updateAnsClick('updateForm')">确 定</el-button>
			</div>
		</el-dialog>

		<!-- 查看考试题 -->
		<el-dialog title="查看考试题" :visible.sync="dialogFormVisibleView">
			<el-form class="demo-viewForm">
				<ul v-for="(key,index) in viewForm" :key="index">
					<li v-if="index=='testDesc' ? false: true">
						<b>{{(index+1)}}</b>{{key}}</li>
				</ul>
				<ol v-for="(i,index) in viewForm.testDesc" :key="index+10">
					<li>
						<b>考试题目{{index+1}}、</b>{{i}}</li>
				</ol>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisibleView = false">退出</el-button>
				<!-- <el-button type="primary" @click="dialogFormVisibleView = false">确 定</el-button> -->
			</div>
		</el-dialog>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<div class="pages">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[3, 4, 5, 6]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</el-col>
	</section>
</template>

<script>
import { mapActions, mapState, mapMutations } from "vuex";
export default {
  data() {
    // 修改表单验证
    var checkNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("题数不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (value < 2) {
            callback(new Error("必须大于一道题"));
          } else {
            callback();
          }
        }
      }, 1000);
    };

    return {
      users: [],
      listLoading: false,
      sels: [], //列表选中列
      dialogFormVisible: false,
      //   新增列表
      addForm: {
        testTitle: "",
        testNumber: 0,
        testTime: "",
        testDesc: []
      },
      // 新增的表单验证
      rules: {
        testTitle: [
          { required: true, message: "请输入考试标题", trigger: "blur" },
          { min: 5, message: "长度,不能小于五个字符", trigger: "blur" }
        ],
        testNumber: [
          {
            type: "number",
            required: true,
            message: "请输入考试题数量",
            trigger: "blur"
          }
          //    { required: true, message: "请输入考试题数量", trigger: "blur" }
        ],
        testTime: [
          { required: true, message: "请输入考试时间", trigger: "blur" }
        ]
      },
      formLabelWidth: "120px",
      formLabelWidth2: "40px",
      viewForm: {},
      dialogFormVisibleView: false,
      // 修改
      dialogFormVisibleUpdate: false,
      updateForm: {
        testTitle: "",
        testNumber: 0,
        testTime: "",
        testDesc: []
      },
      //   修改的表单验证
      rules2: {
        testTitle: [
          { required: true, message: "请输入考试标题", trigger: "blur" }
        ],
        testNumber: [{ validator: checkNum, trigger: "blur" }],
        testTime: [
          { required: true, message: "请输入考试时间", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    ...mapState({
      lists: state => state.teacher.lists,
      currentPage: state => state.teacher.pagiConfig.currentPage,
      pageSize: state => state.teacher.pagiConfig.pageSize,
      totalPage: state => state.teacher.totalPage,
      total: state => state.teacher.total
    })
  },
  methods: {
    ...mapActions([
      "getUserData",
      "potTestData",
      "delTestData",
      "updateTestData"
    ]),
    ...mapMutations(["getPageSize", "getCurrentPage"]),
    //性别显示转换
    // formatSex: function (row, column) {
    // 	return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    // },
    handleSizeChange(val) {
      this.getPageSize(val);
      // this.getUserData()
      this.getUsers();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      // console.log(this.currentPage2)
      //  this.currentPage = val
      // console.log(val);
      this.getCurrentPage(val);
      // this.getUserData()
      this.getUsers();
      console.log(`当前页: ${val}`);
    },
    // 修改考试题
    updateTestClick(item) {
      this.dialogFormVisibleUpdate = true;
      item.testNumber = item.testNumber * 1;
      item.testDesc = JSON.parse(item.testDesc);
      this.updateForm = item;
    },
    // 重置修改模态框
    cancleUpdate(updateForm) {
		console.log(123)
	this.$refs[updateForm].resetFields();
    //   this.dialogFormVisibleUpdate = false;
    //   this.getUsers();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
          this.getUsers();
        })
        .catch(_ => {});
    },
    // 保存修改
    updateAnsClick(updateForm) {
      this.$refs[updateForm].validate(valid => {
        if (valid) {
          this.updateForm.testDesc = JSON.stringify(this.updateForm.testDesc);
          console.log(this.updateForm);
          this.updateTestData(this.updateForm)
            .then(res => {
              this.getUsers();
              this.dialogFormVisibleUpdate = false;
            })
            .catch(err => {
              this.getUsers();
            });
          alert("修改成功");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 查看试题信息
    viewTest(item) {
      this.viewForm = item;
      this.viewForm.testDesc = JSON.parse(item.testDesc);
      this.dialogFormVisibleView = true;
      this.getUsers();
    },
    // 新增时input框中试题数量改变引发的操作
    numChange(val) {
      this.addForm.testNumber = val * 1;
    },
    numChange2(val) {
      this.updateForm.testNumber = val * 1;
    },
    // 删除当前条试题信息
    deltestClick(item) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 点击确定删除时的回调函数 执行删除操作
          this.delTestData(item.id).then(res => {
            this.getUsers();
          });
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          // // 点击取消删除时的回调函数 取消删除操作 并弹出提示框
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 新增按钮
    addAnsClick(addForm) {
      this.$refs[addForm].validate(valid => {
        if (valid) {
          console.log("新增成功");
          this.dialogFormVisible = false;
          this.addForm.testDesc = JSON.stringify(this.addForm.testDesc);
          console.log(this.addForm.testDesc);
          this.potTestData(this.addForm).then(res => {
            this.getUsers();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(addForm) {
      this.$refs[addForm].resetFields();
    //   this.dialogFormVisible = false;
    },
    // 判卷
    Automatic(item) {
      console.log(item);
      this.$router.push({ path: "/form", query: { item: item } });
    },
    //获取用户列表
    getUsers() {
      this.listLoading = true;
      this.getUserData().then(res => {
        this.users = this.lists;
        this.listLoading = false;
      });
    },
    selsChange: function(sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function() {}
  },
  mounted() {
    this.getUsers();
  }
};
</script>

<style>
.box .el-dialog--small {
  width: 67%;
}
.addFormPart {
  display: inline-block;
}
.addFormPart.right {
  width: 68%;
}
.addFormPart.left {
  width: 30%;
}
.pages {
  float: right;
}
</style>